package com.tangyee.home_knowledge.adapter;

import android.annotation.SuppressLint;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.os.AsyncTask;
import android.util.LruCache;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;

import com.tangyee.R;
import com.tangyee.home_knowledge.bean.KnowledgeItem;
import com.tangyee.refreshloadlistview.ZrcListView;

import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.List;

/**
 *   2
 * @author: yu huawen
 * @date: 2019/1/24 21:29
 */
public class KnowsListViewAdapter extends BaseAdapter {

    private List<KnowledgeItem> list;
    private ZrcListView listview;
    private LruCache<String, BitmapDrawable> mImageCache;
    public final String imagePreURL = "https://www.tangyee.com/Content/upload/images/RecipeImages/";

    public KnowsListViewAdapter(List<KnowledgeItem> list) {
        super();
        this.list = list;

        int maxCache = (int) Runtime.getRuntime().maxMemory();
        int cacheSize = maxCache / 10;
        mImageCache = new LruCache<String, BitmapDrawable>(cacheSize) {
            @Override
            protected int sizeOf(String key, BitmapDrawable value) {
                return value.getBitmap().getByteCount();
            }
        };
    }

    @Override
    public int getCount() {
        return list.size();
    }

    @Override
    public Object getItem(int position) {
        return list.get(position);
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    public List<KnowledgeItem> getKnowledgeItemList() {
        return list;
    }

    public void setKnowledgeItemList(List<KnowledgeItem> knowledgeItemList) {
        this.list = knowledgeItemList;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        if (listview == null) {
            listview = (ZrcListView) parent;
        }
        ViewHolder holder = null;
        if (convertView == null) {
            convertView = LayoutInflater.from(parent.getContext()).inflate(R.layout.layout_home_knowledge_listitem, null);
            holder = new ViewHolder();
            holder.image = (ImageView) convertView.findViewById(R.id.ImageKnows);
            holder.title = (TextView) convertView.findViewById(R.id.KnowsTitle);
            holder.summary = (TextView) convertView.findViewById(R.id.KnowsContent);
            holder.date = (TextView) convertView.findViewById(R.id.KnowsTime);
            convertView.setTag(holder);
        } else {
            holder = (ViewHolder) convertView.getTag();
        }

        KnowledgeItem item = list.get(position);
        holder.title.setText(item.getTitle());
        //holder.summary.setText(item.getSummary());
        holder.date.setText(item.getReleaseDate());
        holder.image.setTag(imagePreURL + item.getImage());

        // 如果本地已有缓存，就从本地读取，否则从网络请求数据
        if (mImageCache.get(imagePreURL + item.getImage()) != null) {
            holder.image.setImageDrawable(mImageCache.get(imagePreURL + item.getImage()));
        } else {
            ImageTask it = new ImageTask();
            it.execute(imagePreURL + item.getImage());

        }

        return convertView;

    }

    class ViewHolder {
        ImageView image;
        TextView title, summary, date;
    }

    class ImageTask extends AsyncTask<String, Void, BitmapDrawable> {
        private String imageUrl;

        @Override
        protected BitmapDrawable doInBackground(String... params) {
            imageUrl = params[0];
            Bitmap bitmap = downloadImage();
            @SuppressLint("WrongThread") BitmapDrawable db = new BitmapDrawable(listview.getResources(), bitmap);
            // 如果本地还没缓存该图片，就缓存
            if (mImageCache.get(imageUrl) == null) {
                mImageCache.put(imageUrl, db);
            }

            return db;
        }

        @Override
        protected void onPostExecute(BitmapDrawable result) {
            // 通过Tag找到我们需要的ImageView，如果该ImageView所在的item已被移出页面，就会直接返回null
            ImageView iv = (ImageView) listview.findViewWithTag(imageUrl);
            if (iv != null && result != null) {
                iv.setImageDrawable(result);
            }
        }

        /**
         * 根据url从网络上下载图片
         *
         * @return
         */
        private Bitmap downloadImage() {
            HttpURLConnection con = null;
            Bitmap bitmap = null;
            try {
                URL url = new URL(imageUrl);
                con = (HttpURLConnection) url.openConnection();
                con.setConnectTimeout(5 * 1000);
                con.setReadTimeout(10 * 1000);
                bitmap = BitmapFactory.decodeStream(con.getInputStream());
            } catch (MalformedURLException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                if (con != null) {
                    con.disconnect();
                }
            }

            return bitmap;
        }
    }

}

